package org.ocelot.tunes4j.gui;

import java.awt.Toolkit;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;

import org.ocelot.tunes4j.beans.AudioObject;
import org.ocelot.tunes4j.service.AudioObjectService;
import org.ocelot.tunes4j.taggers.RegistryTagger;
import org.ocelot.tunes4j.taggers.Tagger;

import eu.medsea.mimeutil.MimeUtil;

public class ImportFilesTask extends SwingWorker<Object, Object> {

	private BeanTableModel<AudioObject> model;
	private RegistryTagger registry = null;
	private String strategy = "";
	private List<File> sourceFileList;
	private AudioObjectService service;
	
	public FilenameFilter filefilter = new FilenameFilter() {
		@Override
		public boolean accept(File file, String name) {
			return file.isDirectory() || name.toLowerCase().endsWith(".mp3");
		}
    };
	
    public boolean isValidFile(File file) {
    	boolean result = MimeUtil.getMimeTypes(file).contains("audio/mpeg3");
		return result;
    }
    
    public ImportFilesTask(BeanTableModel<AudioObject> model, String strategy, List<File> sourceFileList,AudioObjectService service) {
//    public ImportFilesTask(BeanTableModel<AudioObject>  model, String strategy, List<File> sourceFileList, AudioObjectService service) {
    		
    	this.model = model;
    	this.registry = new RegistryTagger();
		this.strategy=strategy;
		this.sourceFileList=sourceFileList;
		this.service = service;
    }
    
	@Override
	protected Object doInBackground() throws Exception {
		// Get Files from FileSystem
		List<File> fileList = new ArrayList<File>();
		for (File file : sourceFileList) {
			getFiles(file, fileList);
		}
		// Parse Files
		int size=fileList.size();
		int i = 0;
		Tagger tagger = registry.getInsance(this.strategy);
		while( i < fileList.size() &&  !isCancelled() ) {
			AudioObject bean = tagger.parse(fileList.get(i));
			publish(bean);
			setProgress(100 * (++i) / size);
		}
		return null;
	}
	
	/**
	 * Recursive function that gets Media Files from the FileSystem
	 * @param folder
	 * @param list
	 */
	private void getFiles(File folder, List<File> list){
		if (folder.isDirectory()) {
			for (File file : folder.listFiles(filefilter)) {
				getFiles(file,list);
			}
		} else if (folder.isFile()) {
			if (isValidFile(folder)){
				list.add(folder);
			}
		}
	}

	 /**
     * 
     * Executed in event dispatching thread
     */
    @Override
    public void done() {
        Toolkit.getDefaultToolkit().beep();
    }
    
	@Override
    protected void process(List<Object> chunks) {
        for (Object row : chunks) {
        	AudioObject bean = (AudioObject) row;
        	model.addRow(bean);
        	service.save(bean);
        }
    }
	
}